package swe.user;

import java.security.spec.KeySpec;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;


public class UserManager {
	
	private String name = "USERMANAGER";
	
	private List<User> userList = new ArrayList<User>();
	//private String filename = "/home/a0331084/apache-tomcat-7.0.32/webapps/buyallthestuff/WEB-INF/data/articles.ser";
	//private String filename = "C:/workspace/users.ser";
	
	public List<User> getUserList() {
		return userList;
	}

	public void setUserList(List<User> userList) {
		this.userList = userList;
	}

	public UserManager(UserDAO udao) {
		this.userList = udao.read();
	}
	
	public void register(User user, UserDAO udao) {
		userList.add(user);
		udao.save(userList);
		
		
	}
	
	public boolean login(String name, String password) throws Exception {
		
		for(User i: userList) {
			
			if(authenticate(password, i.getSavedPassword(), i.getSalt(), i)) {
				return true;
			}
		}
		return false;
	}
	
	public User getUserById(int id){
		for(User i: userList) {

			if(i.getiD()==id) {
				return i;
			}
		}
		// ADD EXCEPTION HERE: USER NOT FOUND
		return null;
		
	}
	
//	public boolean isLoggedIn(User user) { 
//	return true;
//}
	
	public boolean authenticate(String attemptedPassword, byte[] encryptedPassword, byte[] salt, User user) throws Exception {
	  byte[] encryptedAttemptedPassword = getEncryptedPassword(attemptedPassword, salt);
	  return Arrays.equals(encryptedPassword, encryptedAttemptedPassword);
	 }
	
	public byte[] getEncryptedPassword(String password, byte[] salt) throws Exception {
		  String algorithm = "PBKDF2WithHmacSHA1";
		  int derivedKeyLength = 160;
		  int iterations = 10000;
		  KeySpec spec = new PBEKeySpec(password.toCharArray(), salt, iterations, derivedKeyLength);
		  SecretKeyFactory f = SecretKeyFactory.getInstance(algorithm);
		  
		  return f.generateSecret(spec).getEncoded();
		 }
}
